/*
 * @Author: wuyang
 * @Description: 用户相关 - 状态管理数据
 * @Date: 2023-01-06 09:15:07
 * @LastEditors: wuyang
 * @LastEditTime: 2023-01-06 14:07:41
 * @FilePath: \vue-ts-vite\src\store\modules\user.ts
 */
import { store } from "@/store";
import { defineStore } from "pinia";
import { login, getInfo, logout } from "@/api/user";
import { appMoudles } from "@/config/app";
import { TOKEN, TIME_STAMP } from "@/constant";
import type { AppState } from "@/config/app";
import { useCache } from "@/hooks/useCache";
import router, { resetRouter } from "@/router";
import { setTimeStamp } from "@/utils/auth";
const { wsCache } = useCache();
export const useUserStore = defineStore({
  id: "vitality-user",
  state: (): AppState => appMoudles,

  getters: {
    // 获取 token
    getToken(): string {
      return this.token;
    },
    // 获取用户信息
    getUserInfo(): any {
      return this.userInfo;
    },
    getHasUerInfo(): boolean {
      return JSON.stringify(this.userInfo) !== "{}";
    },
  },

  actions: {
    /** 存储登录页面显示哪个组件 */
    SET_CURRENTPAGE(value: number) {
      this.currentPage = value;
    },
    /** 修改验证码数据 */
    SET_CAPTCHA(value: string) {
      this.captcha = value;
    },
    /**
     * 删除 token
     */
    resetToken() {
      return new Promise<void>((resolve) => {
        this.token = "";
        // this.userInfo = {};
        wsCache.delete(TOKEN);
        wsCache.delete(TIME_STAMP);
        resetRouter();
        resolve();
      });
    },
    changeState(captcha: string) {
      // 相当于此时的 actions是 Vue模板中的 methods，state是 vue模板中的data
      this.captcha = captcha;
    },
    /**
     * 登录
     * @param userInfo (用户名和密码)
     * @returns
     */
    login(userInfo: LoginFormModule) {
      const { password, username } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password })
          .then((res) => {
            // 存 token
            this.token = res.token as unknown as string;
            wsCache.set(TOKEN, res.token);
            ElMessage({
              message: "登录成功",
              type: "success",
            });
            // 保存登录时间
            setTimeStamp();
            // 跳转至首页
            router.push("/student/home");
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    /**
     * 获取用户信息
     */
    async getuserInfo() {
      const res = await getInfo();
      this.userInfo = res.data;
      this.hasUserInfo = true;
      return res;
    },
    /**
     * 退出登录
     */
    logout() {
      return new Promise<void>((resolve, reject) => {
        // logout()
        //   .then((res) => {
        //     this.token = "";
        //     // this.userInfo = {};
        //     wsCache.delete(TOKEN);
        //     wsCache.delete(TIME_STAMP);
        //     resetRouter();
        //     resolve();
        //   })
        //   .catch((error) => {
        //     reject();
        //   });
        this.token = "";
        // this.userInfo = {};
        wsCache.delete(TOKEN);
        wsCache.delete(TIME_STAMP);
        router.push("/login");
        resetRouter();
        resolve();
      });
    },
  },
  // ...
});

export function useUserStoreHook() {
  return useUserStore(store);
}
